/*
	This file is part of AVRCppLib.

    AVRCppLib is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AVRCppLib is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AVRCppLib.  If not, see <http://www.gnu.org/licenses/>.

    Copyright (C) Maxime Lemonnier 2007-2011
 */

#ifndef EXTERNALINTERRUPTSTEST_H_
#define EXTERNALINTERRUPTSTEST_H_
#include "ExternalInterrupts/ExternalInterrupts.h"
#include "TestCase.h"

class ExternalInterruptTest :  public TestCase<ExternalInterruptTest>
{

	ExternalInterrupt * ei;

	IOAddress excitatingPort;
	IOAddress excitatingDDR;
	uint8_t excitatingPin;
	uint8_t interruptPin;
	static bool calledBack;

public:


	ExternalInterruptTest(const prog_mem * testMethodName_P, TestCase<ExternalInterruptTest>::TestMethod testMethod) : TestCase<ExternalInterruptTest>(testMethodName_P, testMethod)
	{
		excitatingPort = &PORTB;
		excitatingDDR = &DDRB;
		excitatingPin = 5;
		interruptPin = 4;
	}


	static void interruptCallBack()
	{
		calledBack = true;
	}

	void setUp()
	{


		calledBack = false;
		disableInterrupts();
		ei = ExternalInterrupt::getInstance(interruptPin);
	}

	void tearDown()
	{
		calledBack = false;
		disableInterrupts();
	}


	bool testGetInstance()
	{
		return AVRUNIT_ASSERT(!isNull(ei));
	}

	bool testExternalInterruptCallBack()
	{
		*excitatingDDR = bitValue(excitatingPin); // all input except excitatingPin
		*excitatingPort = 0x00;

		bool result = true;
		ei->configure(ExternalInterrupt::RISING_EDGE);
		ei->setInterruptCallBack(ExternalInterruptTest::interruptCallBack);
		delay(100);


		result &= AVRUNIT_ASSERT_TESTNAME(!calledBack, "setInterruptCallBack (before setBit)"); // since we haven't enabled interrupts yet

		setBit(*excitatingPort, excitatingPin);

		result &= AVRUNIT_ASSERT_TESTNAME(!calledBack, "setInterruptCallBack (after setBit, before sei)"); // since we haven't enabled interrupts yet

		clearBit(*excitatingPort, excitatingPin);

		enableInterrupts();
		setBit(*excitatingPort, excitatingPin);
		delay(10);
		disableInterrupts();

		return result & AVRUNIT_ASSERT_TESTNAME(calledBack, "setInterruptCallBack (after int. enable)");
	}

};

bool ExternalInterruptTest::calledBack = false;

#endif /* EXTERNALINTERRUPTSTEST_H_ */
